<template>
  <div class="min-h-screen bg-gray-100">


    <!-- 页面标题 -->
    <div class="bg-cover bg-center bg-no-repeat text-white py-8" style="background-image: url('/images/image.png');">
      <div class="container mx-auto px-4 text-center">
        <h1 class="text-4xl font-bold mb-2">Carbon Border Adjustment Mechanism Results</h1>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="mx-auto px-2 py-2 h-screen flex items-center justify-center">
      <div class="text-center">
        <div class="inline-block animate-spin rounded-full h-16 w-16 border-b-2 border-blue-600 mb-4"></div>
        <p class="text-gray-600 text-lg">Loading data...</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div v-else class="mx-auto px-2 py-2 h-screen" style="margin-top: 10px;">
      <div class="grid grid-cols-1 lg:grid-cols-4 gap-4 mb-4">
        <!-- 个人信息面板 -->
        <div class="bg-white rounded-lg   p-4 lg:col-span-2">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-base font-bold" style="color: #066aa4;">Personal Information</h2>
            <p class="text-sm text-gray-600">Date Range: {{ recordData?.startDate || '2025-01-21' }} - {{
              recordData?.endDate || '2025-05-21' }}</p>
          </div>

          <!-- 关键指标网格 -->
          <div class="grid grid-cols-3 gap-4 mb-6" :class="isExpanded ? 'gap-2' : 'gap-4'">
            <div class="bg-gray-50 rounded-lg" :class="isExpanded ? 'p-2' : 'p-4'">
              <p class="text-lg font-bold  mb-1 " style="color: #17628d;" :class="isExpanded ? 'text-base' : 'text-lg'">
                {{ formattedIndustryName }}</p>
              <p class="text-sm text-gray-600" :class="isExpanded ? 'text-xs' : 'text-sm'">Product Type</p>
            </div>
            <div class="bg-gray-50 rounded-lg" :class="isExpanded ? 'p-2' : 'p-4'">
              <p class="text-lg font-bold text-green-600 mb-1" style="color: #17628d;"  :class="isExpanded ? 'text-base' : 'text-lg'">
                {{ recordData?.params.tanjia }} {{ recordData?.params.currencySymbolTarget }}€/Ton CO₂</p>
              <p class="text-sm text-gray-600" :class="isExpanded ? 'text-xs' : 'text-sm'">Carbon Price</p>
            </div>
            <div class="bg-gray-50 rounded-lg" :class="isExpanded ? 'p-2' : 'p-4'">
              <p class="text-lg font-bold text-yellow-600 mb-1" style="color: #17628d;"  :class="isExpanded ? 'text-base' : 'text-lg'">
                1{{ recordData?.params.currencySymbolHome }} : {{ formattedHuilv }} {{ recordData?.params.currencySymbolTarget }}</p>
              <p class="text-sm text-gray-600" :class="isExpanded ? 'text-xs' : 'text-sm'">Exchange Rate</p>
            </div>
            <div class="bg-gray-50 rounded-lg" :class="isExpanded ? 'p-2' : 'p-4'">
              <p class="text-lg font-bold text-purple-600 mb-1" style="color: #17628d;"  :class="isExpanded ? 'text-base' : 'text-lg'">
                {{ formattedChukouliang }}</p>
              <p class="text-sm text-gray-600" :class="isExpanded ? 'text-xs' : 'text-sm'">Export Volume</p>
            </div>
            <div class="bg-gray-50 rounded-lg" :class="isExpanded ? 'p-2' : 'p-4'">
              <p class="text-lg font-bold text-red-600 mb-1" style="color: #17628d;"  :class="isExpanded ? 'text-base' : 'text-lg'">
                {{ formattedZaiguoneizhifudetanchengben }}</p>
              <p class="text-sm text-gray-600" :class="isExpanded ? 'text-xs' : 'text-sm'">Paid Carbon Cost</p>
            </div>
            <div class="bg-gray-50 rounded-lg" :class="isExpanded ? 'p-2' : 'p-4'">
              <p class="text-lg font-bold text-indigo-600 mb-1" style="color: #17628d;"  :class="isExpanded ? 'text-base' : 'text-lg'">
                {{ formattedMathResult }}</p>
              <p class="text-sm text-gray-600" :class="isExpanded ? 'text-xs' : 'text-sm'">Expected Carbon Tariffs</p>
            </div>
          </div>

          <!-- 百分比指标 -->
          <div class="bg-green-100 rounded-lg mb-6" :class="isExpanded ? 'p-2' : 'p-4'"
            v-if="recordData?.params.lirun && recordData?.params.lirun && recordData?.params.yingshou">
            <div class="flex">
              <div class="flex-1 text-center border-r border-green-200">
                <p class="text-2xl font-bold text-green-600 mb-1" :class="isExpanded ? 'text-lg' : 'text-2xl'">
                  {{ ((recordData?.mathResult / recordData?.params.yingshou) * 100).toFixed(2) }}%</p>
                <p class="text-sm text-gray-600" :class="isExpanded ? 'text-xs' : 'text-sm'">Carbon tax as a percentage
                  of revenue</p>
              </div>
              <div class="flex-1 text-center">
                <p class="text-2xl font-bold text-green-600 mb-1" :class="isExpanded ? 'text-lg' : 'text-2xl'">
                  {{ ((recordData?.mathResult / recordData?.params.lirun) * 100).toFixed(2) }}%</p>
                <p class="text-sm text-gray-600" :class="isExpanded ? 'text-xs' : 'text-sm'">Carbon tax as a percentage
                  of profits</p>
              </div>
            </div>
          </div>

          <!-- 展开/收起按钮 -->
          <div class="bg-orange-100 p-3 rounded-lg">
            <!-- 三个财务指标盒子 -->
            <div v-if="isExpanded">
              <!-- 顶部金色边框 -->
              <div class="h-1  mb-4"></div>

              <!-- 三个财务指标 -->
              <div class="flex justify-between items-center">
                <div class="flex-1 text-center">
                  <p class="text-2xl font-bold text-orange-500 mb-1">{{ formattedRevenue }}</p>
                  <p class="text-sm text-gray-600">Annual revenue</p>
                </div>
                <div class="w-px h-12 bg-gray-300"></div>
                <div class="flex-1 text-center">
                  <p class="text-2xl font-bold text-orange-500 mb-1">{{ formattedProfit }}</p>
                  <p class="text-sm text-gray-600">Annual profit</p>
                </div>
                <div class="w-px h-12 bg-gray-300"></div>
                <div class="flex-1 text-center">
                  <p class="text-2xl font-bold text-orange-500 mb-1">
                    {{ formattedTotalCarbonTax }}</p>
                  <p class="text-sm text-gray-600">Expected carbon tariffs</p>
                </div>
              </div>
            </div>

            <button @click="toggleExpand" class="w-full flex items-center justify-center text-orange-600 font-medium">
              <span>{{ isExpanded ? 'Retract input values' : 'Expand input values' }}</span>
              <svg class="w-4 h-4 ml-2 transition-transform duration-200" :class="{ 'rotate-180': isExpanded }"
                fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
              </svg>
            </button>
          </div>
        </div>

        <!-- CBAM对企业利润影响分析 -->
        <div class="bg-white rounded-lg   p-4 flex flex-col">
          <h2 class="text-base font-bold mb-4" style="color: #066aa4;">Share of CBAM in Corporate Profits</h2>
          <p class="text-sm text-gray-600 mb-4">Impact of Carbon Tax on Corporate Financial Structure（€ Million）</p>

          <!-- 环形图 -->
          <div ref="donutChart" class="w-full flex-1 mb-4"></div>

          <!-- 财务数据 -->


          <!-- <div class="space-y-3 text-sm">
                 <div class="flex justify-between items-center">
                   <span class="text-gray-700">Annual revenue of the enterprise:</span>
                   <span class="font-semibold text-blue-600">€2.5</span>
                 </div>
                 <div class="flex justify-between items-center">
                   <span class="text-gray-700">Estimated cost of carbon tax:</span>
                   <span class="font-semibold text-blue-600">€2.5</span>
                 </div>
                 <div class="flex justify-between items-center">
                   <span class="text-gray-700">Annual profit of the enterprise:</span>
                   <span class="font-semibold text-blue-600">€2.5</span>
                 </div>
                 <div class="flex justify-between items-center">
                   <span class="text-gray-700">The cost of carbon tax will account for:</span>
                   <span class="font-semibold text-blue-600">revenue: 5% profit: 10%</span>
                 </div>
               </div> -->
        </div>

        <!-- 碳排放差异与碳税金额对比 -->
        <div class="bg-white rounded-lg   p-4 flex flex-col">
          <h2 class="text-base font-bold mb-4" style="color: #066aa4;">Carbon Emission Gap vs. Carbon Tax Amount</h2>
          <p class="text-sm text-gray-600 mb-4">Emission Reduction vs. Tax Buiden in Production Processes</p>

          <!-- 折线图 -->
          <div ref="lineChart" class="w-full flex-1"></div>
        </div>
      </div>

      <!-- 第二行图表 -->
      <div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4" style="min-height: 400px;">
        <!-- 散点图 -->
        <div class="bg-white rounded-lg   p-4 flex flex-col">
          <h2 class="text-base font-bold mb-4" style="color: #066aa4;">Comparison of Emission Factors
            Across Production Processes</h2>
          <div ref="scatterChart" class="w-full flex-1" style="min-height: 300px;"></div>
        </div>

        <!-- 雷达图 -->
        <!-- <div class="bg-white rounded-lg   p-4 flex flex-col">
          <h2 class="text-base font-bold mb-4" style="color: #066aa4;">Comparison of Emission Factors with Industry Average and EU Standard</h2>
          <p class="text-sm text-gray-600 mb-4">Comparison of carbon emission radars in various stages (€1,000,000)</p>
          <div ref="radarChart" class="w-full flex-1" style="min-height: 300px;"></div>
        </div> -->

        <!-- 柱状图 -->
        <div class="bg-white rounded-lg   p-4 flex flex-col">
          <h2 class="text-base font-bold mb-4" style="color: #066aa4;">Comparison of Emission Factors with Industry Average and EU Standard</h2>
          <div ref="barChart" class="w-full flex-1" style="min-height: 300px;"></div>
        </div>

        <!-- 饼图 -->
        <div class="bg-white rounded-lg   p-4 flex flex-col">
          <h2 class="text-base font-bold mb-4" style="color: #066aa4;">Proportion of Tax Burden in Corporate Profits</h2>
          <div ref="pieChart" class="w-full flex-1" style="min-height: 300px;"></div>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, ref, computed } from 'vue'

// 页面元数据
definePageMeta({
  layout: false
})

// 获取路由参数
const route = useRoute()
const recordId = route.query.recordId

// 图表容器引用
const donutChart = ref(null)
const lineChart = ref(null)
const scatterChart = ref(null)
const radarChart = ref(null)
const barChart = ref(null)
const pieChart = ref(null)

// 展开/收起状态
const isExpanded = ref(false)

// 数据状态
const recordData = ref(null)
const loading = ref(true)

// ==================== 工具函数 ====================

/**
 * 格式化 industryName 为 Title Case（每个单词首字母大写）
 */
const capitalizeIndustryName = (name) => {
  if (!name) return ''
  return name
    .split(' ')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
    .join(' ')
}

/**
 * 格式化大数字为 Million/Billion/Trillion 表示
 * 如果小数点后都是0，则不显示小数点
 */
const formatLargeNumber = (value, decimals = 2) => {
  if (value === null || value === undefined || isNaN(value)) {
    return '0'
  }
  
  const num = Number(value)
  if (num === 0) {
    return '0'
  }
  
  const absNum = Math.abs(num)
  const sign = num < 0 ? '-' : ''
  
  let result = ''
  if (absNum >= 1e12) {
    const formatted = (absNum / 1e12).toFixed(decimals)
    result = `${sign}${parseFloat(formatted)} Trillion`
  } else if (absNum >= 1e9) {
    const formatted = (absNum / 1e9).toFixed(decimals)
    result = `${sign}${parseFloat(formatted)} Billion`
  } else if (absNum >= 1e6) {
    const formatted = (absNum / 1e6).toFixed(decimals)
    result = `${sign}${parseFloat(formatted)} Million`
  } else {
    const formatted = absNum.toFixed(decimals)
    result = `${sign}${parseFloat(formatted)}`
  }
  
  return result
}

// ==================== 计算属性 ====================

// industryName 格式化
const formattedIndustryName = computed(() => 
  capitalizeIndustryName(recordData.value?.industryName)
)

// 数字格式化（带单位）
const formattedChukouliang = computed(() => 
  `${formatLargeNumber(recordData.value?.params.chukouliang)} Ton/time`
)

const formattedZaiguoneizhifudetanchengben = computed(() => {
  // 原始数值单位是"万"，需要乘以10000转换为实际数值
  const valueInTenThousand = recordData.value?.params.zaiguoneizhifudetanchengben || 0
  const actualValue = valueInTenThousand * 10000
  return `${formatLargeNumber(actualValue)} ${recordData.value?.params.currencySymbolTarget || '€'}`
})

const formattedMathResult = computed(() => 
  `${formatLargeNumber(recordData.value?.mathResult)} ${recordData.value?.params.currencySymbolTarget || '€'}`
)

const formattedRevenue = computed(() => 
  `${formatLargeNumber(recordData.value?.revenue)} ${recordData.value?.params.currencySymbolTarget || '€'}`
)

const formattedProfit = computed(() => 
  `${formatLargeNumber(recordData.value?.profit)} ${recordData.value?.params.currencySymbolTarget || '€'}`
)

// 汇率格式化（保留4位小数）
const formattedHuilv = computed(() => {
  const huilv = recordData.value?.params.huilv
  return huilv ? parseFloat(huilv).toFixed(4) : '0.0000'
})

const formattedTotalCarbonTax = computed(() => {
  const mathResult = recordData.value?.mathResult || 0
  // zaiguoneizhifudetanchengben 单位是"万"，需要乘以10000
  const zaiguonei = (recordData.value?.params.zaiguoneizhifudetanchengben || 0) * 10000
  const total = mathResult + zaiguonei
  return `${formatLargeNumber(total)} ${recordData.value?.params.currencySymbolTarget || '€'}`
})

// 切换展开/收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

// 获取记录详情
const fetchRecordDetail = async () => {
  if (!recordId) return

  try {
    const { userApi } = await import('~/public/utils/api')
    const response = await userApi.getRecordDetail(recordId)

    if (response.code === 200) {
      recordData.value = response.data
      updateChartsWithData(response.data)
    }
  } catch (error) {
    console.error('Failed to fetch record detail:', error)
  } finally {
    loading.value = false
  }
}

// 根据接口数据更新图表
const updateChartsWithData = (data) => {
  // 解析图表数据
  const doughnutData = data.doughnutChart ? JSON.parse(data.doughnutChart) : {}
  const lineData = data.lineChart ? JSON.parse(data.lineChart) : {}
  const bubbleData = data.bubbleChart ? JSON.parse(data.bubbleChart) : {}
  const radarData = data.radarChart ? JSON.parse(data.radarChart) : {}
  const columnData = data.columnChart ? JSON.parse(data.columnChart) : {}
  const pieData = data.pieChart ? JSON.parse(data.pieChart) : {}

  // 重新初始化图表
  setTimeout(() => {
    if (donutChart.value) initDonutChart(doughnutData)
    if (lineChart.value) initLineChart(lineData)
    if (scatterChart.value) initScatterChart(bubbleData)
    if (radarChart.value) initRadarChart(radarData)
    if (barChart.value) initBarChart(columnData)
    if (pieChart.value) initPieChart(pieData)
  }, 100)
}

// 初始化环形图
const initDonutChart = (data = {}) => {
  const chart = echarts.init(donutChart.value)
  const colorPalette = [
    '#10B981', '#3B82F6', '#60A5FA', '#FF6B6B',
    '#F59E0B', '#8B5CF6', '#EC4899', '#06B6D4',
    '#84CC16', '#64748B'
  ];

  // 检查是否有有效数据
  const hasValidData = Object.keys(data).length > 0;

  let chartData;
  let showNoDataMessage = false;

  if (hasValidData) {
    // 有真实数据时使用接口数据
    chartData = Object.entries(data).map(([key, value], index) => ({
      value: parseFloat(value) || 0,
      name: key,
      itemStyle: {
        color: colorPalette[index % colorPalette.length]
      }
    }));
  } else {
    // 无数据时显示示例数据，并标记为示例
    chartData = [
      { value: 250, name: 'Carbon tax cost (Example)', itemStyle: { color: '#10B981' } },
      { value: 1500, name: 'Net profit (Example)', itemStyle: { color: '#3B82F6' } },
      { value: 750, name: 'Other operating costs (Example)', itemStyle: { color: '#60A5FA' } }
    ];
    showNoDataMessage = true;
  }

  // 获取容器宽度用于响应式调整
  const containerWidth = donutChart.value.offsetWidth;
  const legendWidth = Math.min(containerWidth * 0.35, 120);

  const option = {
    title: showNoDataMessage ? {
      text: 'No Data Available',
      subtext: '(Showing Example Data)',
      left: 'center',
      top: 'middle',
      textStyle: {
        fontSize: 14,
        color: '#999',
        fontWeight: 'normal'
      },
      subtextStyle: {
        fontSize: 12,
        color: '#ccc'
      }
    } : undefined,
    tooltip: {
      trigger: 'item',
      formatter: showNoDataMessage ?
        '{b}: {c} ({d}%)<br/><span style="color: #999;">Example Data</span>' :
        '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      left: 'center',
      data: chartData.map(item => item.name),
      textStyle: {
        fontSize: 12,
        width: legendWidth,
        overflow: 'truncate'
      },
      tooltip: {
        show: true,
        formatter: function(name) {
          return name; // 显示完整名称
        }
      },
      itemWidth: 10,
      itemHeight: 10,
      itemGap: 16
    },
    series: [
      {
        name: 'Financial Structure',
        type: 'pie',
        radius: ['30%', '55%'],
        center: ['50%', '45%'], // 图表居中并稍微上移，为底部图例留出空间
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: chartData
      }
    ]
  }
  chart.setOption(option)
}

// 初始化条形图（横向显示）
const initLineChart = (data = {}) => {
  const chart = echarts.init(lineChart.value)

  // 解析数据结构: { "emissionsReduction": 481.229500, "taxPayment": 67911.31 }
  let emissionsReduction, taxPayment
  
  if (Object.keys(data).length > 0 && data.emissionsReduction !== undefined && data.taxPayment !== undefined) {
    // 使用接口返回的数据
    emissionsReduction = parseFloat(data.emissionsReduction) || 0
    taxPayment = parseFloat(data.taxPayment) || 0
  } else {
    // 使用默认数据
    emissionsReduction = 499.5
    taxPayment = 139225255.72
  }

  // 格式化数值：保留两位小数（如果有小数），没有小数则不处理
  const formatValue = (val) => {
    if (val === null || val === undefined || isNaN(val)) {
      return ''
    }
    if (val % 1 === 0) {
      return val  // 整数不处理
    }
    return parseFloat(val.toFixed(2))  // 有小数则保留两位
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        // 找到有值的那个系列（非null）
        const validParam = params.find(p => p.value !== null && p.value !== undefined)
        if (!validParam) return ''
        
        const value = formatValue(validParam.value)
        return `${validParam.name}<br/>${validParam.marker}${value}`
      }
    },
    legend: {
      show: false  // 隐藏图例，因为X轴已经说明了类别
    },
    grid: {
      top: '10%',
      bottom: '15%',
      left: '12%',
      right: '12%'
    },
    xAxis: {
      type: 'category',
      data: ['Emissions Reduction', 'Tax Payment'],
      axisLabel: {
        rotate: 0,
        fontSize: 11,
        interval: 0  // 强制显示所有标签
      }
    },
    yAxis: [
      {
        type: 'value',
        name: 'Emissions Reduction\n(tCO₂)',
        position: 'left',
        nameTextStyle: {
          fontSize: 10,
          align: 'center'
        },
        nameGap: 10,
        axisLabel: {
          formatter: function(value) {
            if (value >= 1000000) {
              return (value / 1000000).toFixed(1) + 'M'
            } else if (value >= 1000) {
              return (value / 1000).toFixed(1) + 'K'
            }
            return value.toFixed(0)
          }
        }
      },
      {
        type: 'value',
        name: 'Tax Payment\n(€)',
        position: 'right',
        nameTextStyle: {
          fontSize: 10,
          align: 'center'
        },
        nameGap: 10,
        axisLabel: {
          formatter: function(value) {
            if (value >= 1000000) {
              return (value / 1000000).toFixed(1) + 'M'
            } else if (value >= 1000) {
              return (value / 1000).toFixed(1) + 'K'
            }
            return value.toFixed(0)
          }
        }
      }
    ],
    series: [
      {
        name: 'Emissions Reduction',
        type: 'bar',
        yAxisIndex: 0,
        data: [emissionsReduction, null],  // 第一个柱子显示排放减少量，第二个位置为空
        itemStyle: {
          color: '#3B82F6'  // 蓝色
        },
        barWidth: '40%',
        barGap: '-100%',  // 两个系列的柱子重叠在同一位置
        label: {
          show: true,
          position: 'top',
          fontSize: 10,
          formatter: function(params) {
            return params.value ? formatValue(params.value) : ''
          }
        }
      },
      {
        name: 'Tax Payment',
        type: 'bar',
        yAxisIndex: 1,
        data: [null, taxPayment],  // 第一个位置为空，第二个柱子显示税额
        itemStyle: {
          color: '#10B981'  // 绿色
        },
        barWidth: '40%',
        label: {
          show: true,
          position: 'top',
          fontSize: 10,
          formatter: function(params) {
            return params.value ? formatValue(params.value) : ''
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化散点图
const initScatterChart = (data = {}) => {
  const chart = echarts.init(scatterChart.value)

  // 扩展颜色池（9种颜色）
  const colorPalette = [
    '#F59E0B', // 1. 橙色
    '#3B82F6', // 2. 蓝色
    '#10B981', // 3. 绿色
    '#EF4444', // 4. 红色
    '#8B5CF6', // 5. 紫色
    '#EC4899', // 6. 粉色
    '#06B6D4', // 7. 青色
    '#84CC16', // 8. 黄绿色
    '#64748B'  // 9. 灰蓝色
  ]

  // 检查是否有有效的API数据
  const hasApiData = Object.keys(data).length > 0

  let categories = []
  let values = []
  let itemColors = []

  if (hasApiData) {
    // ✅ 直接使用后端返回的键值对，无任何计算或映射
    categories = Object.keys(data)  // X轴类别（后端已返回友好名称）
    values = Object.values(data).map(v => parseFloat(v) || 0)  // Y轴数值
    
    // 根据顺序分配颜色（循环使用颜色池）
    itemColors = categories.map((_, index) => colorPalette[index % colorPalette.length])
  } else {
    // 默认示例数据
    categories = ['Example 1', 'Example 2', 'Example 3']
    values = [30, 25, 45]
    itemColors = [colorPalette[0], colorPalette[1], colorPalette[2]]
  }

  // 格式化数值：保留两位小数（如果有小数），整数不处理
  const formatValue = (val) => {
    if (val === null || val === undefined || isNaN(val)) return ''
    if (val % 1 === 0) return val  // 整数
    return parseFloat(val.toFixed(2))  // 小数保留两位
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        const value = formatValue(params.value)
        return `${params.name}: ${value}`
      }
    },
    legend: {
      data: categories,
      top: 10,
      textStyle: {
        fontSize: 12
      },
      // 如果类别太多，图例可能会很长，考虑使用滚动
      type: categories.length > 6 ? 'scroll' : 'plain'
    },
    grid: {
      top: '20%',
      bottom: '20%',
      left: '10%',
      right: '10%'
    },
    xAxis: {
      type: 'category',  // ✅ 类别轴
      data: categories,  // ✅ X轴显示字段名（后端已友好化）
      name: '',
      nameLocation: 'middle',
      nameGap: 35,
      axisLabel: {
        // 如果字段数量较多或较长，旋转30度显示
        rotate: categories.length > 3 || categories.some(c => c.length > 15) ? 30 : 0,
        interval: 0,  // 显示所有标签
        fontSize: 11
      }
    },
    yAxis: {
      type: 'value',  // ✅ 数值轴
      name: 'Emission difference（kgCO₂/t）',  // ✅ Y轴标题
      nameTextStyle: {
        fontSize: 12
      },
      axisLabel: {
        formatter: function(value) {
          // 小数值范围(0-100)，简单显示即可
          if (value % 1 === 0) {
            return value  // 整数
          }
          return value.toFixed(1)  // 小数保留1位
        }
      }
    },
    series: [{
      name: 'Emission Factor',
      type: 'scatter',
      data: values,  // ✅ 直接使用后端数值，无任何计算
      symbolSize: 12,
      itemStyle: {
        // 动态颜色：每个点根据索引分配颜色
        color: (params) => itemColors[params.dataIndex]
      },
      emphasis: {
        scale: true,
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        }
      }
    }]
  }
  
  chart.setOption(option)
  
  // 响应式处理
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化雷达图
const initRadarChart = (data = {}) => {
  const chart = echarts.init(radarChart.value)

  // 使用接口数据或默认数据
  const companyVal = parseFloat(data.companyVal) || 80
  const industryVal = parseFloat(data.industryVal) || 90
  const euVal = parseFloat(data.euVal) || 60
  const maxVal = Math.max(companyVal, industryVal, euVal, 100)

  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      data: Object.keys(data).length > 0 ? ['EU standards', 'The Company', 'Industry Average'] : ['The Company', 'Industry Average', 'EU standards'],
      bottom: 0,
      textStyle: {
        fontSize: 12
      }
    },
    grid: {
      top: '10%',
      bottom: '15%',
      left: '10%',
      right: '10%'
    },
    radar: {
      indicator: [
        { name: 'Emission Factor', max: maxVal * 1.2 }
      ]
    },
    series: [
      {
        name: 'Emission Factors',
        type: 'radar',
        data: [
          {
            value: [companyVal],
            name: 'The Company',
            itemStyle: { color: '#3B82F6' }
          },
          {
            value: [industryVal],
            name: 'Industry Average',
            itemStyle: { color: '#10B981' }
          },
          {
            value: [euVal],
            name: 'EU standards',
            itemStyle: { color: '#F59E0B' }
          }
        ]
      }
    ]
  }
  chart.setOption(option)
}

// 初始化柱状图
const initBarChart = (data = {}) => {
  const chart = echarts.init(barChart.value)

  // 使用接口数据或默认数据
  const companyVal = parseFloat(data.companyVal) || 100
  const industryVal = parseFloat(data.industryVal) || 120
  const euVal = parseFloat(data.euVal) || 60

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: Object.keys(data).length > 0 ? ['EU standards', 'The Company', 'Industry Average'] : ['The Company', 'Industry Average', 'EU standards'],
      top: 10,  // 将图例移到顶部
      textStyle: {
        fontSize: 12
      }
    },
    grid: {
      top: '20%',    // 增加顶部空间给图例
      bottom: '25%', // 增加底部空间给X轴标题
      left: '10%',
      right: '10%'
    },
    xAxis: {
      type: 'category',
      data: ['Carbon emissions per unit product'],
      name: 'Carbon emissions per unit product（kgCO₂/t）',  // 添加底部标题
      nameLocation: 'middle',    // 标题位置在中间
      nameGap: 35               // 标题与轴的距离
    },
    yAxis: {
      type: 'log',  // Y轴使用对数刻度
      min: 1,       // 对数刻度的最小值必须大于0
      max: Math.max(companyVal, industryVal, euVal) * 1.2,
      logBase: 100,  // 改用100为底的对数，刻度按100倍递增
      splitNumber: 3,  // 进一步减少刻度数量
      minorTick: {
        show: false  // 隐藏次要刻度线
      },
      axisLabel: {
        formatter: function(value) {
          // 格式化标签，只显示整数
          if (value >= 1000000) {
            return Math.round(value / 1000000) + 'M'
          } else if (value >= 1000) {
            return Math.round(value / 1000) + 'K'
          }
          return Math.round(value)
        }
      }
    },
    series: [
      {
        name: 'The Company',
        type: 'bar',
        data: [companyVal],
        itemStyle: { color: '#3B82F6' },
        barGap: '30%',  // 增加柱子之间的间隔
        barWidth: '20%'  // 减小柱子宽度，让间隔更明显
      },
      {
        name: 'Industry Average',
        type: 'bar',
        data: [industryVal],
        itemStyle: { color: '#60A5FA' },
        barWidth: '20%'
      },
      {
        name: 'EU standards',
        type: 'bar',
        data: [euVal],
        itemStyle: { color: '#F59E0B' },
        barWidth: '20%'
      }
    ]
  }
  chart.setOption(option)
}

// 初始化饼图
const initPieChart = (data = {}) => {
  const chart = echarts.init(pieChart.value)

  // 使用接口数据或默认数据（去掉 taxProfit）
  const chartData = Object.keys(data).length > 0 ? [
    { value: Math.abs(parseFloat(data.taxCost) || 0), name: 'Tax Cost', itemStyle: { color: '#F59E0B' } },
    { value: Math.abs(parseFloat(data.other) || 0), name: 'Other', itemStyle: { color: '#3B82F6' } }
  ] : [
    { value: 250, name: 'Carbon tax cost', itemStyle: { color: '#F59E0B' } },
    { value: 750, name: 'Other operating costs', itemStyle: { color: '#3B82F6' } }
  ]

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 0,
      data: chartData.map(item => item.name),
      textStyle: {
        fontSize: 12
      }
    },
    grid: {
      top: '10%',
      bottom: '15%',
      left: '10%',
      right: '10%'
    },
    series: [
      {
        name: 'Financial Distribution',
        type: 'pie',
        radius: '50%',
        data: chartData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

onMounted(() => {
  // 如果有recordId，获取详情数据
  if (recordId) {
    fetchRecordDetail()
  } else {
    // 没有recordId时，使用默认数据初始化图表，显示短暂加载
    setTimeout(() => {
      if (donutChart.value) initDonutChart()
      if (lineChart.value) initLineChart()
      if (scatterChart.value) initScatterChart()
      if (radarChart.value) initRadarChart()
      if (barChart.value) initBarChart()
      if (pieChart.value) initPieChart()
      loading.value = false
    }, 800) // 给用户一个短暂的加载体验
  }
})
</script>
<style>
.sx {
  font-size: 0.7rem;
}

.bl {
  color: #0066a1;
}

.text-sm {
  font-size: 0.7rem;
}

.text-base {
  font-size: 0.9rem;
}
</style>